﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.Common.Domain;
using Traceability.Common.Dtos;
using Traceability.Common.Infrastructure.InterFaces;
using Traceability.Enum;

namespace Traceability.Bais.API.Appliction.Command.Roless
{
    public class RolesCreateHandler : IRequestHandler<RolesCreateCommon, Result>
    {
        IBaseRepository<Roles> rolesRep;
        IBaseRepository<RolesPermission> _rolespermissionsRep;
        //IMapper mapper;
        public RolesCreateHandler(IBaseRepository<Roles> _rolesRep, IBaseRepository<RolesPermission> rolespermissionsRep, IMapper _mapper)
        {
            rolesRep = _rolesRep;
           
            _rolespermissionsRep = rolespermissionsRep;
        }
        public async Task<Result> Handle(RolesCreateCommon request, CancellationToken cancellationToken)
        {

            var result = new Result() { Code = (int)CommonErrorCode.add };
            try
            {
                var roles =  new Roles
                {
                    RolesName = request.RolesName,
                    Status = request.Status,
                    CreatedTime = DateTime.Now,
                    createdOwnerId = 1,
                    UpdatedTime = DateTime.Now,
                    UpdateOwnerId = 1,
                    IsDelete = false,
                    DeleteOwnerId = 1,
                    DeleteTime = DateTime.Now
                };
                var n = await rolesRep.AddAsync(roles);
               
                foreach (var item in request.permissionIds)
                {
                    await _rolespermissionsRep.AddAsync(new RolesPermission
                    {
                        PermissionId = item,
                        RolesId = roles.RolesId
                    });
                }
                result.Code = (int)CommonErrorCode.sucess;
                result.Msg = "添加成功";


            }
            catch (Exception)
            {
                result.Msg = "添加失败";
                throw;
            }
           

            return result;
            //using (TransactionScope tran = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.Serializable }))
            //{
            //    tran.Complete();
            //}
         
        }
    }
}
